package com.audaque.springboot.foshanupload.web.lic.service.impl;

import com.audaque.springboot.foshanupload.core.util.ResourceUtil;
import com.audaque.springboot.foshanupload.web.lic.service.LicenseVerifyService;
import com.audaque.springboot.foshanupload.web.lic.verify.LicenseVerify;
import com.audaque.springboot.foshanupload.web.lic.verify.bo.LicenseVerifyParam;
import de.schlichtherle.license.LicenseContent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author zgb
 * @desc ...
 * @date 2022-10-24 18:01:45
 */
@Slf4j
@Service
public class LicenseVerifyServiceImpl implements LicenseVerifyService {


    /**
     * 证书subject
     */
    @Value("${licenseClient.subject}")
    private String subject;

    /**
     * 公钥别称
     */
    @Value("${licenseClient.publicAlias}")
    private String publicAlias;

    /**
     * 访问公钥库的密码
     */
    @Value("${licenseClient.storePass}")
    private String storePass;

    /**
     * 证书生成路径
     */
    @Value("${licenseClient.licensePath}")
    private String licensePath;

    /**
     * 密钥库存储路径
     */
    @Value("${licenseClient.publicKeysStorePath}")
    private String publicKeysStorePath;

    @Override
    public boolean install() {
        String publicKeysStorePath1;
        try {
            publicKeysStorePath1 = ResourceUtil.getPathByHutoolResourceUtil(publicKeysStorePath);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (StringUtils.isNotBlank(licensePath)) {
            log.debug("++++++++ 开始安装证书 ++++++++");
            LicenseVerifyParam param = new LicenseVerifyParam();
            param.setSubject(subject);
            param.setPublicAlias(publicAlias);
            param.setStorePass(storePass);
            param.setLicensePath(licensePath);
            param.setPublicKeysStorePath(publicKeysStorePath1);
            LicenseVerify licenseVerify = new LicenseVerify();
            //安装证书
            try {
                LicenseContent installResult = licenseVerify.install(param);
                log.debug("installResult:"+installResult);
                return installResult==null?false:true;
            } catch (Exception e) {
                log.error(e.getMessage());
                return false;
            }
        }
        return false;
    }

    @Override
    public boolean verify() {
        LicenseVerify licenseVerify = new LicenseVerify();
        //校验证书是否有效
        boolean verifyResult = licenseVerify.verify();
       return verifyResult;
    }
}
